﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FFSupplier.ServiceCore.Utility
{
    public static class CrmDataTable
    {
        public static List<T> AsEntityEnumerable<T>(SqlDataReader reader)
        {
            DataTable table = new DataTable();
            table.Load(reader);
            return table.AsEnumerable().Select(row =>
            {
                return new EntityHelper<T>(table.Columns, row).GenerateEntity();
            }).ToList();
        }

        private class EntityHelper<T>
        {
            private readonly DataColumnCollection _columns;
            private readonly DataRow _row;

            public EntityHelper(DataColumnCollection columns, DataRow row) { _columns = columns; _row = row; }

            public T GenerateEntity()
            {
                T result = System.Activator.CreateInstance<T>();
                foreach (DataColumn col in _columns)
                {
                    ((dynamic)result).Attributes.Add(col.ColumnName.ToLower(), _row[col]);
                }
                return result;
            }
        }
    }
}
